package com.example.demo_mvi.viewmodel

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.demo_mvi.http.MyService
import com.example.demo_mvi.http.RetrofitManager
import com.example.demo_mvi.intent.MyIntent
import com.example.demo_mvi.state.MyUIState
import kotlinx.coroutines.channels.Channel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.consumeAsFlow
import kotlinx.coroutines.flow.filter
import kotlinx.coroutines.flow.flow
import kotlinx.coroutines.launch

/**
 * @author yaotianxue
 * @description
 * @date 2025/1/9
 */
class MyViewModel:ViewModel() {
    val newsChannel = Channel<MyIntent>(Channel.UNLIMITED) //通道

    private val _uiState = MutableStateFlow<MyUIState>(MyUIState.Loading) //可变的流，不暴露
    val uiState: StateFlow<MyUIState> = _uiState.asStateFlow() //不可变的流，暴露出去


    init {
        hanldeIntent()
    }
    //222222:根据不同的intent发起不同网络请求
    private fun hanldeIntent() {
        viewModelScope.launch {
            newsChannel.consumeAsFlow().collect{
                when(it){
                    is MyIntent.GetVideos -> getVideoData()
                    is MyIntent.GetBanner -> getBannerData()
                }
            }
        }
    }

    private fun getBannerData() {

    }

    //3333333:根据不同的网络请求结果，更新state
    private fun getVideoData(){
        viewModelScope.launch {
            //发起网络请求
            flow {
                val video = RetrofitManager.getRetrofit().create(MyService::class.java).video()
                emit(video)
            }.filter { it-> it != null }
                .catch {exception->
                    _uiState.value = MyUIState.Error(exception.message.toString())
                }
                .collect{it->
                    if(it.code == 200){
                        _uiState.value = MyUIState.Success(it.data)
                    }
                }

        }
    }



}